package service

import (
	"errors"
	"wms/internal/model"
	"wms/internal/model/request"
	"wms/pkg/database"

	"gorm.io/gorm"
)

// CustomerService 客户服务
type CustomerService struct {
	db *gorm.DB
}

// NewCustomerService 创建客户服务
func NewCustomerService() *CustomerService {
	return &CustomerService{
		db: database.GetDB(),
	}
}

// CreateCustomer 创建客户
func (s *CustomerService) CreateCustomer(req *request.CustomerCreateRequest) error {
	var existingCustomer model.Customer
	err := s.db.Where("name = ?", req.Name).First(&existingCustomer).Error
	if err == nil {
		return errors.New("客户名称已存在")
	}
	if !errors.Is(err, gorm.ErrRecordNotFound) {
		return err
	}

	// 检查联系电话是否存在
	if req.Phone != "" {
		err = s.db.Where("phone = ?", req.Phone).First(&existingCustomer).Error
		if err == nil {
			return errors.New("联系电话已存在")
		}
		if !errors.Is(err, gorm.ErrRecordNotFound) {
			return err
		}
	}

	customer := model.Customer{
		Name:    req.Name,
		Contact: req.Contact,
		Phone:   req.Phone,
		Email:   req.Email,
		Address: req.Address,
		Remark:  req.Remark,
	}

	return s.db.Create(&customer).Error
}

// UpdateCustomer 更新客户
func (s *CustomerService) UpdateCustomer(req *request.CustomerUpdateRequest) error {
	var customer model.Customer
	err := s.db.First(&customer, req.ID).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return errors.New("客户不存在")
		}
		return err
	}

	// 检查名称是否存在
	if req.Name != customer.Name {
		var existingCustomer model.Customer
		err := s.db.Where("name = ? AND id != ?", req.Name, req.ID).First(&existingCustomer).Error
		if err == nil {
			return errors.New("客户名称已存在")
		}
		if !errors.Is(err, gorm.ErrRecordNotFound) {
			return err
		}
	}

	// 检查联系电话是否存在
	if req.Phone != "" && req.Phone != customer.Phone {
		var existingCustomer model.Customer
		err := s.db.Where("phone = ? AND id != ?", req.Phone, req.ID).First(&existingCustomer).Error
		if err == nil {
			return errors.New("联系电话已存在")
		}
		if !errors.Is(err, gorm.ErrRecordNotFound) {
			return err
		}
	}

	// 更新客户信息
	updates := map[string]interface{}{
		"name":    req.Name,
		"contact": req.Contact,
		"phone":   req.Phone,
		"email":   req.Email,
		"address": req.Address,
		"remark":  req.Remark,
	}

	return s.db.Model(&customer).Updates(updates).Error
}

// DeleteCustomer 删除客户
func (s *CustomerService) DeleteCustomer(id uint) error {
	// 检查客户是否存在
	var customer model.Customer
	err := s.db.First(&customer, id).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return errors.New("客户不存在")
		}
		return err
	}

	// TODO: 检查客户是否有关联的订单
	// 先注释掉，因为Order模型不存在
	/*
		var count int64
		err = s.db.Model(&model.Order{}).Where("customer_id = ?", id).Count(&count).Error
		if err != nil {
			return err
		}
		if count > 0 {
			return errors.New("客户存在关联订单，无法删除")
		}
	*/

	return s.db.Delete(&customer).Error
}

// GetCustomerByID 根据ID获取客户
func (s *CustomerService) GetCustomerByID(id uint) (*model.Customer, error) {
	var customer model.Customer
	err := s.db.First(&customer, id).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, errors.New("客户不存在")
		}
		return nil, err
	}
	return &customer, nil
}

// ListCustomers 获取客户列表
func (s *CustomerService) ListCustomers(req *request.CustomerListRequest) ([]model.Customer, int64, error) {
	var customers []model.Customer
	var total int64

	query := s.db.Model(&model.Customer{})

	// 根据条件筛选
	if req.Keyword != "" {
		query = query.Where("name LIKE ? OR contact LIKE ? OR phone LIKE ?",
			"%"+req.Keyword+"%", "%"+req.Keyword+"%", "%"+req.Keyword+"%")
	}

	// 统计总数
	err := query.Count(&total).Error
	if err != nil {
		return nil, 0, err
	}

	// 分页查询
	offset := (req.Page - 1) * req.PageSize
	err = query.Offset(offset).Limit(req.PageSize).Find(&customers).Error
	if err != nil {
		return nil, 0, err
	}

	return customers, total, nil
}

// GetCustomerList 获取客户列表
func (s *CustomerService) GetCustomerList(keyword string, status, level, page, pageSize int) ([]model.Customer, int64, error) {
	db := database.GetDB()
	var customers []model.Customer
	var total int64

	// 构建查询
	query := db.Model(&model.Customer{})

	// 根据条件过滤
	if keyword != "" {
		query = query.Where("code LIKE ? OR name LIKE ?", "%"+keyword+"%", "%"+keyword+"%")
	}
	if status > 0 {
		query = query.Where("status = ?", status)
	}
	if level > 0 {
		query = query.Where("level = ?", level)
	}

	// 获取总数
	if err := query.Count(&total).Error; err != nil {
		return nil, 0, err
	}

	// 分页查询
	offset := (page - 1) * pageSize
	if err := query.Offset(offset).Limit(pageSize).Order("id ASC").Find(&customers).Error; err != nil {
		return nil, 0, err
	}

	return customers, total, nil
}

// BatchDeleteCustomer 批量删除客户
func (s *CustomerService) BatchDeleteCustomer(ids []uint) error {
	return s.db.Delete(&model.Customer{}, ids).Error
}
